package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserLoginMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jt
 * @date 2021/4/21 15:20
 */
@Service
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserLoginMapper, ApUser> implements ApUserLoginService {

    /*@Resource
    private ApUserLoginMapper apUserMapper;*/

    @Override
    public ResponseResult login(LoginDto dto) {
//        1. 校验参数
        if (dto.getEquipmentId() == null && (StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPassword()))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//        2. 查询登录用户
        if (StringUtils.isNotBlank(dto.getPassword()) && StringUtils.isNotBlank(dto.getPhone())) {
            ApUser apUser = baseMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getStatus, 0).eq(ApUser::getPhone, dto.getPhone()));
            if (ObjectUtils.isEmpty(apUser)) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户状态为锁定或手机号不存在");
            }
//            获取数据库的密码
            String password = apUser.getPassword();
            String digestAsHex = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
//        3. 和数据库的密码进行比对
            if (!password.equals(digestAsHex)) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"手机号或者密码错误");
            }
            Map<String, Object> map = new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else {
//        4. 通过设备id登陆的设置userId
            Map<String, Object> map = new HashMap<>();
//            走了else说明是设备id登录 userId存为0
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }

}
